/**
 * 全局事件订阅混入
 */
import Vue from 'vue'
import { Component } from 'vue-property-decorator';
import event from '@/utils/events'

@Component
export default class EventsMixin extends Vue {
  [index: number]: string
  public eventsListen: string[]

  constructor() {
    super()
    this.eventsListen = ['getData']
  }

  // 事件监听器
  get events() {
    return event
  }

  public mounted() {
    // 进入页面时默认把getData方法加入订阅
    this._eventListen()
  }

  public activated() {
    this._eventListen()
  }

  // 事件订阅
  public _eventListen() {
    this.$nextTick(() => {
      this.eventsListen.forEach((item: any) => {
        this.events.listen('update', () => {
          this[item] && (this[item] as any)()
        })
      })
    })
  }

  // 组件销毁时移除所有订阅update的事件
  public deactivated() {
    this.events.remove('update')
  }

  // 组件销毁时移除所有订阅update的事件
  public destroyed() {
    this.events.remove('update')
  }
}
